package com.sina.mysql.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

/**
 * @ClassName MysqlRoutingDataSource
 * @Description:
 * @Author 段浩杰
 * @Date 2018/8/22 17:59
 * @Version 1.0
 */
public class MysqlRoutingDataSource extends AbstractRoutingDataSource {

    private static final Logger LOG = LoggerFactory.getLogger( MysqlRoutingDataSource.class );

    private static final String MASTER_PATTER = "m%s";

    private static final String SLAVER_PATTER = "s%s";


    @Override
    protected Object determineCurrentLookupKey() {
        String pattern;
        if (TransactionDefinitionHolder.isReadOnly()) {
            pattern = SLAVER_PATTER;
        } else {
            pattern = MASTER_PATTER;
        }
        String lookupKey = String.format( pattern, "0" );
        LOG.debug( "datasource : {},thread :{}", lookupKey, Thread.currentThread().getName() );
        return lookupKey;
    }
}
